//
//  TrackDetailVC.m
//  KEREN
//
//  Created by MW on 2023/4/7.
//

#import "TrackDetailVC.h"

@interface TrackDetailVC ()<MAMapViewDelegate>
@property (nonatomic, strong) UIButton *backBtn;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, assign) CLLocationCoordinate2D firstCoordinate;
@property (nonatomic, assign) int currentIndx;
@property (nonatomic, strong) NSMutableArray *pointArrM;
@end

@implementation TrackDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    MAMapView *mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, DEVICE_HEIGHT - 320)];
    mapView.delegate = self;
    mapView.zoomLevel = 19;
    ///把地图添加至view
    [self.view addSubview:mapView];

    _backBtn = [UIButton setButtonWithImage:@"back" cornerRadius:0 backColor:[UIColor clearColor]];
    [self.view addSubview:_backBtn];
    [_backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(40);
        make.left.offset(24);
        make.top.offset(9 + STATUSBAR_HEIGHT);
    }];
    [_backBtn addTarget:self action:@selector(backBtnClick) forControlEvents:UIControlEventTouchUpInside];
    MATraceManager *trace = [[MATraceManager alloc] init];
    if(_model.track_list && _model.track_list.count > 0){
        for (int i = 0; i <_model.track_list.count; i ++) {
            NSDictionary *dict =  _model.track_list[i];
            if([dict[@"lat"] floatValue] < 360){
                MATraceLocation *location = [[MATraceLocation alloc] init];
                location.loc = [[GDMapTool sharedInstance] AMapCoordinateConvertWithLatitude:[dict[@"lat"] floatValue] andLongitude:[dict[@"lng"] floatValue]];
                //CLLocationCoordinate2D coor = [[GDMapTool sharedInstance] AMapCoordinateConvertWithLatitude:[dict[@"lat"] floatValue] andLongitude:[dict[@"lng"] floatValue]];
                location.time = [dict[@"t"] longLongValue] * 1000;
                location.speed = [dict[@"s"] doubleValue];
                location.angle = [dict[@"b"] doubleValue];
                [self.pointArrM  addObject:location];
            }
        }
    }
    
    [trace queryProcessedTraceWith:self.pointArrM type:AMapCoordinateTypeAMap processingCallback:^(int index, NSArray<MATracePoint *> *points) {
        DDLogInfo(@"points = %@,self.pointArrM = %@",points,self.pointArrM);
    } finishCallback:^(NSArray<MATracePoint *> *points, double distance) {
        DDLogInfo(@"points = %@,self.pointArrM = %@",points,self.pointArrM);
        CLLocationCoordinate2D commonPolylineCoords[points.count];
        for (int i = 0; i < points.count; i ++) {
            MATracePoint *location = points[i];

            CLLocationCoordinate2D amapcoord = AMapCoordinateConvert(CLLocationCoordinate2DMake(location.latitude,location.longitude), AMapCoordinateTypeAMap);

            commonPolylineCoords[i] = amapcoord;
            if(i == 0){
                MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];
                pointAnnotation.coordinate = amapcoord;
                
                //设置地图的定位中心点坐标
                mapView.centerCoordinate = amapcoord;
                //将点添加到地图上，即所谓的大头针
                self.firstCoordinate = amapcoord;
                [mapView addAnnotation:pointAnnotation];
            }
            if(i == points.count - 1){
                MAPointAnnotation *endpointAnnotation = [[MAPointAnnotation alloc] init];
                endpointAnnotation.coordinate = amapcoord;
                //设置地图的定位中心点坐标
                mapView.centerCoordinate = amapcoord;
                //将点添加到地图上，即所谓的大头针
                [mapView addAnnotation:endpointAnnotation];
            }
        }
        MAPolyline *commonPolyline = [MAPolyline polylineWithCoordinates:commonPolylineCoords count:points.count];

      // 在地图上添加折线对象
      [mapView addOverlay: commonPolyline];
    } failedCallback:^(int errorCode, NSString *errorDesc) {

    }];

    [self bottomView];

}
- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id <MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[MAPolyline class]])
    {
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:overlay];
        polylineRenderer.lineWidth    = 8.f;
        polylineRenderer.strokeColor  = Color_7ACC00;
        polylineRenderer.lineJoinType = kMALineJoinRound;
        polylineRenderer.lineCapType  = kMALineCapRound;
        return polylineRenderer;
    }
    return nil;
}
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation {
    if([annotation isKindOfClass:[MAUserLocation class]]){
        return nil;
    }

    //大头针标注
    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {//判断是否是自己的定位气泡，如果是自己的定位气泡，不做任何设置，显示为蓝点，如果不是自己的定位气泡，比如大头针就会进
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        MAAnnotationView *annotationView = (MAAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (annotationView == nil) {
            annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }

        
        annotationView.frame = CGRectMake(0, 0, 20, 24);
        annotationView.canShowCallout = YES;       //设置气泡可以弹出，默认为NO
        annotationView.draggable = YES;
        //设置标注可以拖动，默认为NO
        if(_firstCoordinate.latitude == annotation.coordinate.latitude){
            annotationView.image = [[UIImageManager shareInstance] setPointImageWithTitle:@"起"];
        }else{
            annotationView.image = [[UIImageManager shareInstance] setPointImageWithTitle:@"终"];
        }
        return annotationView;
    }

    return nil;
}

- (void)backBtnClick{
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSMutableArray *)pointArrM{
    if(!_pointArrM){
        _pointArrM = [NSMutableArray array];
    }
    return _pointArrM;
}

- (UIView *)bottomView{
    if(!_bottomView){
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, DEVICE_HEIGHT - 336, DEVICE_WIDTH, 336)];
        _bottomView.backgroundColor = Whire_Color;
        _bottomView.layer.mask = [CAShapeLayer clipsToBounds:_bottomView.bounds Corners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(25, 25)];
        UIImageView *iconImage = [[UIImageView alloc] init];
        [iconImage sd_setImageWithURL:[NSURL URLWithString:[UserInfoManager sharedInstance].currentDeviceInfo.photo] placeholderImage:[UIImage imageNamed:@"devcie_defalaut_icon"] options:SDWebImageRefreshCached];
        [_bottomView addSubview:iconImage];
        [iconImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(24);
            make.width.height.offset(48);
            make.top.offset(10);
        }];
        UILabel *timeLbl = [UILabel setLblText:[[DeteManager shareInstance] timeFormatted:_model.start_time]  font:BFont(20) withColor:Black_Color inSubView:_bottomView];
        [timeLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(iconImage.mas_right).offset(10);
            make.centerY.equalTo(iconImage);
        }];
        [UIView setLineViewWithframe:CGRectMake(24, 68, DEVICE_WIDTH - 48, 1) forinView:_bottomView];
        
        UIImageView *startPointImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"device_start_point"]];
        [_bottomView addSubview:startPointImage];
        [startPointImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(24);
            make.width.height.offset(12);
            make.top.offset(82);
        }];
        
        UIImageView *lineImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"device_line_point"]];
        [_bottomView addSubview:lineImage];
        [lineImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(startPointImage);
            make.top.equalTo(startPointImage.mas_bottom).offset(8);
            make.width.offset(2);
            make.height.offset(48);
        }];
        UIImageView *endPointImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"device_end_point"]];
        [_bottomView addSubview:endPointImageView];
        [endPointImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(24);
            make.width.height.offset(12);
            make.top.equalTo(lineImage.mas_bottom).offset(8);
        }];
        UILabel *startLbl = [UILabel setLblText:@"起点地址" font:Font(12) withColor:Color_86898E inSubView:_bottomView];
        [startLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(startPointImage.mas_right).offset(8);
            make.centerY.equalTo(startPointImage);
        }];
        UILabel *startPointLbl = [UILabel setLblText:_model.start_name font:Font(16) withColor:Color_333333 inSubView:_bottomView];
        [startPointLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(startPointImage.mas_right).offset(8);
            make.top.equalTo(startLbl.mas_bottom).offset(4);
            make.right.offset(-24);
        }];
        startPointLbl.numberOfLines = 0;
        UILabel *endLbl = [UILabel setLblText:@"终点地址" font:Font(12) withColor:Color_86898E inSubView:_bottomView];
        [endLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(endPointImageView.mas_right).offset(8);
            make.centerY.equalTo(endPointImageView);
        }];
        UILabel *endPointLbl = [UILabel setLblText:_model.end_name font:Font(16) withColor:Color_333333 inSubView:_bottomView];
        [endPointLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(endPointImageView.mas_right).offset(8);
            make.top.equalTo(endLbl.mas_bottom).offset(4);
            make.right.offset(-24);
        }];
        endPointLbl.numberOfLines = 0;


        [UIView setLineViewWithframe:CGRectMake(24, 226, DEVICE_WIDTH - 48, 1) forinView:_bottomView];
        
        NSArray *titleArr = @[@"行驶里程数",@"花费时长",@"最高时速",@"平均时速"];
        for (int i = 0; i < 4; i ++) {
            UIView *layerView = [[UIView alloc] initWithFrame:CGRectMake(0, 236, DEVICE_WIDTH / 4, 55)];
            [_bottomView addSubview:layerView];
            UILabel *titleLbl = [UILabel setLblText:titleArr[i] font:Font(12) withColor:Color_86898E inSubView:layerView];
            titleLbl.frame = CGRectMake(DEVICE_WIDTH / 4 * i, 10, DEVICE_WIDTH / 4, 16);
            titleLbl.textAlignment = NSTextAlignmentCenter;
            UILabel *decLbl = [UILabel setLblText:@"" font:Font(24) withColor:Black_Color inSubView:layerView];
            decLbl.frame = CGRectMake(DEVICE_WIDTH / 4 * i, 30, DEVICE_WIDTH / 4, 24);
            if(i == 0){
                decLbl.attributedText = [NSAttributedString getAttributeWith:@[@"km"] string:[NSString stringWithFormat:@"%0.1fkm",_model.mileage / 1000.0] attributeFont:Font(14)];
            }else if (i == 1){
                decLbl.attributedText = [NSAttributedString getAttributeWith:@[@"min"] string:[NSString stringWithFormat:@"%ldmin",(long)(_model.end_time - _model.start_time) / 60] attributeFont:Font(14)];
            }else if (i == 2){
                decLbl.attributedText = [NSAttributedString getAttributeWith:@[@"km/h"] string:[NSString stringWithFormat:@"%ldkm/h",_model.max_speed] attributeFont:Font(14)];
            }else{
                decLbl.attributedText = [NSAttributedString getAttributeWith:@[@"km/h"] string:[NSString stringWithFormat:@"%ldkm/h",_model.avg_speed] attributeFont:Font(14)];

            }
        }
        [self.view addSubview:_bottomView];
    }
    return _bottomView;
}

@end
